﻿using AutoMapper;
using socialnetworkApp.Domain.Dto.Input;
using socialnetworkApp.Domain.Dto.Output;
using socialnetworkApp.Domain;
using socialnetworkApp.Domain.Manager;
using socialnetworkApp.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Tokens;
using socialnetworkApp.Core.JwtService;
using Microsoft.Extensions.Caching.Memory;

namespace socialnetworkApp.Service.JobService
{
    public class JobService : IJobService
    {
        private readonly JobManager  _jobManager;
        private readonly IMapper _mapper;
        private readonly IAuthenticateService _authenservice;
        private readonly IMemoryCache _memoryCache;
        public JobService(JobManager  jobManager, IMapper mapper, IAuthenticateService authenticateService, IMemoryCache memoryCache)
        {
            _jobManager = jobManager;
            _mapper = mapper;
            _authenservice = authenticateService;
            _memoryCache = memoryCache;
        }

        /// <summary>
        /// 搜索职位信息
        /// </summary>
        /// <param name="searchJobListInput"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ResponseResult<JobListingOutput>> GetJobListingList(SearchJobListInput searchJobListInput)
        {
            JobListingOutput jobListingOutput = new JobListingOutput();
               JobListing jobListing = new JobListing {Job_Title=searchJobListInput.JobTitle,
                   Location=searchJobListInput.Location,
                   Education_Required=searchJobListInput.EducationRequired,
                   Salary_Range=searchJobListInput.SalaryRange,
                   Company_Name=searchJobListInput.CompanyName
               };
             var jobListingList = await  _jobManager.SearchJobList(jobListing);
            var list =   _mapper.Map<List<JobListingdata>>(jobListingList);
            var pageslist = list.Skip((searchJobListInput.PageNo - 1) * searchJobListInput.PageSize).Take(searchJobListInput.PageSize).ToList();
            var HrUserlist = await _jobManager.GetHrUser();
            foreach (var item in pageslist)
            {
                foreach (var useritem in HrUserlist)
                {
                    if (item.u_Id.Equals(useritem.User_Id))
                    {
                        item.nickname = useritem.Nickname;
                    }
                }
            }
            long count = list.LongCount();
            //Math.Ceiling：向上进位取整。
            //总页码
            int pageCount = (int)Math.Ceiling(count * 1.0 / searchJobListInput.PageSize);

            jobListingOutput.Size = searchJobListInput.PageSize;
            jobListingOutput.Total = (int)count;
            jobListingOutput.Pages = (int)count;
            jobListingOutput.JobListingdata = pageslist;
        

            return ResponseResult<JobListingOutput>.SuccessResult(jobListingOutput);
        }

        public async Task<ResponseResult<JobUserInfoOutput>> GetJobUserInfo(string userId)
        {
            if (string.IsNullOrEmpty(userId))
            {
                return ResponseResult<JobUserInfoOutput>.Result(ResultStatus.UnprocessableParam,null,"参数错误！") ;
            }
            JobUsers jobUsers = new JobUsers {User_Id=userId };
          var result =await  _jobManager.FindUser(jobUsers);
           var userinfo =  _mapper.Map<JobUserInfoOutput>(result);


            return ResponseResult<JobUserInfoOutput>.SuccessResult(userinfo);
            
        }


        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="loginInfoDto"></param>
        /// <returns></returns>
        public async Task<ResponseResult<LoginInfoOutput>> UserLogin(loginInfoDto loginInfoDto)
        {
            JobUsers users = new JobUsers { Username = loginInfoDto.Username, Password = loginInfoDto.Password };

            if (!loginInfoDto.Password.IsNullOrEmpty())
            {


                var result = await _jobManager.login(users);
                if (result != null)
                {
                    //登录成功签发token
                    string? token = null;
                    if (_authenservice.IsAuthenticated(loginInfoDto.Username, loginInfoDto.Password, result.User_Id, out token))
                    {
                        LoginInfoOutput loginInfoOutput = new LoginInfoOutput { Token = token };

                        return ResponseResult<LoginInfoOutput>.SuccessResult(loginInfoOutput);
                    }


                }
                return ResponseResult<LoginInfoOutput>.Result(0, null, "用户名或密码错误");
            }
            return ResponseResult<LoginInfoOutput>.Result(0, null, "密码不能为空！");



        }

        /// <summary>
        /// 验证码登录（注册）
        /// </summary>
        /// <param name="userLoginInput"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ResponseResult<LoginInfoOutput>> UserValidateCodeLogin(UserLoginInput userLoginInput)
        {
            //判断用户验证码和
            var CacheCode = _memoryCache.Get(userLoginInput.Email);
            if (CacheCode == null)
            {
                return ResponseResult<LoginInfoOutput>.Result(ResultStatus.Error, null, "您没发送验证码！");
            }
            if (!string.IsNullOrEmpty(CacheCode.ToString()))
            {
                if (CacheCode.Equals(userLoginInput.ValidateCode))
                {
                    var id = Guid.NewGuid().ToString();
                    var nickName = "新用户" + Guid.NewGuid().ToString();
                    var role =Convert.ToInt32(userLoginInput.Role);
                    JobUsers users = new JobUsers { Email = userLoginInput.Email };

                    var result = await _jobManager.IsExistUser(users);
                    Users InserUser;
                    //判断用户是否注册到数据库中了,没注册就注册账号
                    if (result == null)
                    {
                        JobUsers InserUsers = new JobUsers { Email = userLoginInput.Email, User_Id = id,Role=role, Nickname = nickName, Password = "123456" };
                        if (Convert.ToInt32(await _jobManager.AddUser(InserUsers)) <= 0)
                        {
                            return ResponseResult<LoginInfoOutput>.Result(ResultStatus.Error, null, "服务器异常！");
                        }
                    }
                    //登录成功签发token
                    string? token = null;
                    if (_authenservice.IsAuthenticated(userLoginInput.Email, userLoginInput.ValidateCode, result == null ? id : result.User_Id, out token))
                    {
                        LoginInfoOutput loginInfoOutput = new LoginInfoOutput { Token = token };
                        //登录成功三次存储的验证码
                        _memoryCache.Remove(userLoginInput.Email);
                        return ResponseResult<LoginInfoOutput>.SuccessResult(loginInfoOutput);
                    }


                }
                return ResponseResult<LoginInfoOutput>.Result(ResultStatus.Error, null, "验证码不正确！");
            }
            return ResponseResult<LoginInfoOutput>.Result(ResultStatus.Error, null, "验证码不正确或没有发送验证信息！");

        }


    }
}
